<div id="Cindex">
    <div class="row">
        <h1>
            开始多人协作
        </h1>
    </div>
    <br>
    <div class="row">
        <div class="col-xs-3">
            <div class="row">
                <div class="col-xs-12">
                    <input type="text" class="form-control" v-model="username" placeholder="请填写协作时显示的用户名，单机无需填写">
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12">
                    <br>
                    当前工程： {{currentProject==""?"请先选择工程":currentProject.name}}
                </div>
            </div>
        </div>
        <div class="col-xs-2"></div>
        <div class="col-xs-5">
            <div class="row">
                <div class="col-xs-8">
                    <input type="text" class="form-control" v-model="port" placeholder=" 端口号,默认:54876">
                </div>
                <div class="col-xs-4">
                    <button class="btn" @click="openServer()">开启协作服务器</button>

                </div>

            </div>
            <div class="row">
                <div class="col-xs-12"></div>
            </div>
            <div class="row">
                <div class="col-xs-4">
                    <input type="text" class="form-control" v-model="ip" placeholder="服务器ip，请填写协作服务器ip ">
                </div>
                <div class="col-xs-4">
                    <input type="text" class="form-control" v-model="port" placeholder=" 端口号,默认:54876">
                </div>
                <div class="col-xs-4">
                    <button class="btn" @click="connectServer()">连接协作服务器</button>
                </div>
            </div>
        </div>
        <div class="col-xs-2">
            <button class="btn" @click="ipctest() ">
                node.js ping测试
            </button>
            <button class="btn" @click="postTest">数据库测试</button>
        </div>

    </div>
</div>
<hr>
<div id="Cmain">
    <ul class="nav nav-tabs">
        <li class="active"><a href="###" data-target="#tab2Content1" data-toggle="tab">最高级系统</a></li>
        <li><a href="###" data-target="#tab2Content2" data-toggle="tab">功能电路</a></li>
        <li><a href="###" data-target="#tab2Content3" data-toggle="tab">元器件</a></li>
    </ul>
    <div class="tab-content" style="border: 1px soild #fff">
        <div class="tab-pane fade active in" id="tab2Content1">
            <!-- 操作按钮区域，前期添加按钮只用来测试网络功能-->
            <nav class="navbar navbar-default" role="navigation">
                <ul class="nav navbar-nav nav-justified">
                    <li><a data-toggle="modal" data-target="#modelProject" data-backdrop="static">添加系统</a></li>
                </ul>
            </nav>
        </div>
        <div class="tab-pane fade" id="tab2Content2">
            <nav class="navbar navbar-default" role="navigation">
                <ul class="nav navbar-nav nav-justified">
                    <li><a data-toggle="modal" data-target="#modelCircle" data-backdrop="static">添加功能电路</a></li>
                </ul>
            </nav>>
        </div>
        <div class="tab-pane fade" id="tab2Content3">
            <nav class="navbar navbar-default" role="navigation">
                <ul class="nav navbar-nav nav-justified">
                    <li><a data-toggle="modal" data-target="#modelItem" data-backdrop="static">添加元件</a></li>
                </ul>
            </nav>




            <!--测试区域-->
            <div id="itemTest">

            </div>
        </div>
    </div>

    <!-- 对话框HTML -->

    <div class="modal fade" id="modelProject">
        <div class="modal-dialog">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span
                        class="sr-only">关闭</span></button>
                <h4 class="modal-title">系统</h4>
            </div>
            <div class="modal-body">
                <p>添加系统页面...</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary">添加</button>
            </div>
        </div>
    </div>
    <div class="modal fade" id="modelCircle">
        <div class="modal-dialog">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span
                        class="sr-only">关闭</span></button>
                <h4 class="modal-title">电路</h4>
            </div>
            <div class="modal-body">
                <p>添加电路页面...</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary">添加</button>
            </div>
        </div>
    </div>
    <div class="modal fade" id="modelItem">
        <div class="modal-dialog">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span>
                    <span class="sr-only">关闭</span></button>
                <h4 class="modal-title">元器件</h4>
            </div>
            <div class="modal-body">
                <input type="text" class="form-control" v-model="item_test_text">
                <p>添加元器件页面...</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" @click="addItem">添加元件</button>
            </div>
        </div>
    </div>
</div>



<script>

    var vm_index = new Vue({
        el: "#Cindex",
        data: {
            port: 54876,
            ip: "127.0.0.1",
            username: "",
            client: "",
            server: "",
            currentProject: "",//当前项目
            type: 0,//type表示当前客户端的类型，{0，服务器，1客户端}
            users: []//用于保存服务器与客户端的长连接
        },
        methods: {
            pm: function (msg) {//包装消息
                return JSON.stringify({
                    username: this.username,
                    msg: msg
                });
            },
            ipctest: function () {
                ipc.send("ping"); //在这里向后台发送消息
            },
            openServer: function () {
                //上面代码是检查输入错误的，这里我自己测试，就暂时没有做错误检查
                /*
                开启服务器的业务代码
                */
                if (this.currentProject == "") {
                    //alert("请先选择或者新建一个项目!");
                    return;
                }
                if (this.username == "") {
                    //alert("请先设置客户端名字");
                    return;
                }
                this.type = 0;//设定当前为服务器
                var net = require("net");

                var server = net.createServer(function (socket) {
                    // 创建socket服务端，每一个socket对应一个与客户端的链接
                    var add = socket.remoteAddress + ':' + socket.remotePort;
                    console.log('connect: ' + add);
                    vm_index.$data.users.push(socket);//保存长链接，用于在消息更新的时候发送消息
                    //设定服务器的回调函数
                    socket.setEncoding('utf-8');
                    //接收到数据
                    socket.on('data', function (data) {
                        console.log(add + ' client send:' + data);
                        var users = vm_index.$data.users;
                        //服务器收到消息以后，将这个消息向所有客户端推送
                        for (var i = 0; i < users.length; i++) {
                            //遍历每一个客户端，发送消息
                            users[i].write(data);
                        }
                        var obj = JSON.parse(data);
                        $("#itemTest").html($("#itemTest").html() + obj.username + " : " + obj.msg + "<br>");

                    });
                    socket.write(vm_index.pm('Connected!'));//客户端连接后，发送欢迎消息
                    //数据错误事件
                    socket.on('error', function (exception) {
                        console.log('socket error:' + exception);
                        socket.end();
                    });
                    //客户端关闭事件
                    socket.on('close', function (data) {
                        console.log(add + ' client closed!');
                    });
                }).listen(this.port);
                this.server = server;
                //服务器监听事件
                server.on('listening', function () {
                    console.log("server listening:" + server.address().port);
                });
                //服务器错误事件
                server.on("error", function (exception) {
                    console.log("server error:" + exception);
                });

            },
            connectServer: function () { //连接服务器的业务操作
                this.type = 1;//设定标识当前程序为客户端
                var net = require('net');
                var port = this.port;
                var host = this.ip;

                this.client = new net.Socket();
                var client = this.client;
                //创建socket客户端
                client.setEncoding('utf-8');
                //连接到服务端
                client.connect(port, host, function () {
                    client.write(vm_index.pm('hello server'));
                    //向端口写入数据到达服务端
                });
                client.on('data', function (data) {
                    console.log('from server:' + data);
                    var obj = JSON.parse(data);
                    $("#itemTest").html($("#itemTest").html() + obj.username + " : " + obj.msg + "<br>");
                    //得到服务端返回来的数据
                });
                client.on('error', function (error) {
                    //错误出现之后关闭连接
                    console.log('error:' + error);
                    client.destory();
                });
                client.on('close', function () {
                    //正常关闭连接
                    console.log('Connection closed');
                });
            },
            sendMsg: function (Msg) {//统一服务器和客户端的发送端口
                if (this.type == 1) {
                    this.client.write(Msg);//这一句，只是客户端向服务器发送消息
                }
                else {
                    //服务器的话，遍历当前所有客户端长连接，依次发送
                    var users = vm_index.$data.users;
                    //服务器收到消息以后，将这个消息向所有客户端推送
                    for (var i = 0; i < users.length; i++) {
                        //遍历每一个客户端，发送消息
                        users[i].write(Msg);
                    }
                    var obj = JSON.parse(Msg);
                    $("#itemTest").html($("#itemTest").html() + obj.username + " : " + obj.msg + "<br>");
                }
            },
            postTest: function () {
                ipc.send(
                    "db"//向后台查询一个
                );

            }

        }
    })

    var vm_main = new Vue({//页面主要逻辑的显示部分
        el: "#Cmain",
        data: {
            item_test_text: ""
        },
        methods: {
            addItem: function () {
                if (this.item_test_text == "") {
                    //alert("请输入内容");
                    return;
                }
                //满足条件，发送数据
                vm_index.sendMsg(vm_index.pm(this.item_test_text));
                //$("#itemTest").html($("#itemTest").html() + vm_index.$data.username + " : " + this.item_test_text + "<br>");
            }
        }
    })
    //统一接受从main.js中传回的消息
    ipc.on("callback", (sys, msg) => {
        console.log(msg);
    });

</script>